<template>
  <div class="box">
    <div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline" style="margin-top: 20px; margin-left: 30px;">
        <div class="box3" :model="afv" v-if="isDataVisible" :data="tableData" style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-form-item label="客户姓名">
            <el-input v-model="pageParams.name" placeholder="请输入客户姓名" clearable />
          </el-form-item>
          <el-form-item label="客户手机">
            <el-input v-model="pageParams.phone" placeholder="请输入客户手机号码" clearable />
          </el-form-item>
          <el-form-item label="归属人">
            <el-input v-model="pageParams.owner" placeholder="请输入商机归属人" clearable />
          </el-form-item>
          <br>
          <el-form-item label="跟进时间" style="font-weight: 700;">
            <div class="line" />
            <div class="block">
              <el-date-picker style="font-weight: 400;" type="datetimerange" start-placeholder="开始日期"
                end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                time-format="A hh:mm:ss" />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="search">搜索</el-button>
            <el-button icon="Refresh" @click="reset">重置</el-button>
          </el-form-item>
        </div>
        <br>
        <el-form-item>
          <div class="flex-right">
            <div>
              <el-button type="primary" icon="Plus" plain @click="show">新增</el-button>
              <el-button type="success" icon="Edit" @click="edit" :disabled="businessId.length === 0"
                plain>修改</el-button>
              <el-button type="danger" :disabled="businessId.length === 0" @click="deleteClue" icon="Delete"
                plain>删除</el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div style="margin-left: 1200px; margin-top: -50px; margin-bottom: 10px;">
      <el-button :icon="Search" circle class="box8" @click="display" />
      <el-button :icon="Refresh" circle @click="reset" />
    </div>
    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" style="margin-left: 40px;">
      </el-table-column>
      <el-table-column label="客户姓名" property="name" align="center">
      </el-table-column>
      <el-table-column property="phone" label="手机号码" align="center" />
      <el-table-column property="owner" label="商机归属" show-overflow-tooltip align="center" />
      <el-table-column property="createTime" label="创建时间" width="240" align="center" />
      <el-table-column label="商机状态" align="center">
        <template v-slot="scope">
          <el-tag v-if="scope.row.status == 1" type="primary">已分配</el-tag>
          <el-tag v-if="scope.row.status == 2" type="warning">未分配</el-tag>
          <el-tag v-if="scope.row.status == 3" type="info">回收</el-tag>
        </template>
      </el-table-column>
      <el-table-column property="nextTime" label="下次跟进时间" width="240" align="center" />
      <el-table-column property="创建时间" label="操作" align="center" width="200">
        <template v-slot="scope">
          <el-button icon="Pointer" v-if="scope.row.status == 1" style="border: none; color: #90A3FF;" align="center"
            @click="getxiangqing(scope.row.businessId)">分配</el-button>
          <el-button icon="TopRight" v-if="scope.row.status == 1 && scope.row.owner == 'admin01'"
            style="border: none; color: #90A3FF;" align="center" @click="goToCreate(scope.row)">跟进</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-container">
      <div class="demo-pagination-block">
        <el-pagination style="margin-top: 30px; margin-right: 20px;" background v-model:current-page="currentPage4"
          v-model:page-size="pageSize4" :page-sizes="[10, 20, 30, 40]" :size="size" :disabled="disabled"
          :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <!-- 新增 -->
    <el-dialog v-model="dialogFormVisible" :title="title" width="700">
      <el-form :model="ruleForm" ref="ruleFormRef" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="ruleForm.phone" placeholder="请输入手机号码" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="name">
              <el-input v-model="ruleForm.name" placeholder="请输入客户姓名" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="渠道来源">
              <el-select v-model="formInline.region" placeholder="渠道来源" clearable>
                <el-option v-for="item in channelList" :key="item.value" :label="item.channelName"
                  :value="item.channelId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动信息">
              <el-select v-model="formInline.region" placeholder="活动信息" clearable>
                <!-- <el-option label="Zone one" value="shanghai" />
                <el-option label="Zone two" value="beijing" /> -->
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户性别">
              <el-radio-group v-model="radio">
                <el-radio :value="3">男</el-radio>
                <el-radio :value="6">女</el-radio>
                <el-radio :value="9">未知</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户年龄">
              <el-input-number v-model="num" :min="6" @change="handleChange" placeholder="年龄" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="微信号">
              <el-input v-model="ruleForm.weixin" placeholder="请输入微信号码" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="QQ号码">
              <el-input v-model="ruleForm.qq" placeholder="请输入QQ号码" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配 -->
    <el-dialog v-model="dialogOverflowVisible" :title="title" width="700" draggable overflow>
      <el-form :model="ruleForm" ref="ruleFormRef" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="归属部门" prop="departmentId" required>
              <el-select v-model="ruleForm.departmentId" placeholder="请选择归属部门" clearable @change="onDepartmentChange">
                <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分配给" prop="assignUser" required>
              <el-select v-model="ruleForm.assignUser" placeholder="选择用户" clearable>
                <el-option v-for="item in assignUserOptions.filter(u => u.departmentId === ruleForm.departmentId)"
                  :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleAssign">
            确认
          </el-button>
          <el-button @click="dialogOverflowVisible = false">取消</el-button>

        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>

import { useRouter } from 'vue-router'
import { ref, onMounted, nextTick, reactive, } from 'vue'
import type { ComponentSize, FormInstance } from 'element-plus'
import { list, add, clueDel, updata, detail, getBusinessOptions, xiangqing, clueAssign } from "@/api/business/index"
const radio = ref(1)
import {
  Search,
  Refresh,
  Pointer,
  TopRight
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus';
const value2 = ref('')
let total = ref(0)
let title = ref('')
const formInline = reactive({
  user: '',
  region: '',
  date: '',
})

const onSubmit = () => {
  console.log('submit!')
}
// interface User {
//   date: string
//   name: string
//   address: string
// }
const tableData: any = ref([])
const pageParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  phone: '',
  owner: '',
})


// 点击按钮折叠

const isDataVisible = ref(true); // 初始设为 true，默认显示数据
const display = () => {
  isDataVisible.value = !isDataVisible.value; // 取反，切换显示状态
};



const businessId = ref<any[]>([]);
const currentRow = ref<any>(null); // 当前选中行
const multipleSelection = ref<any[]>([]); // 所有选中项
// 表格多选事件，把选中项的 businessId 放进 businessId
const handleSelectionChange = (val: any[]) => {
  businessId.value = val.map(item => item.businessId).filter(id => typeof id === 'number' && !isNaN(id));
  multipleSelection.value = val;
  currentRow.value = val.length === 1 ? val[0] : null;
};
// 分配赋值
const dialogOverflowVisible = ref(false)
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
const ruleFormRef = ref<FormInstance>()
// ruleForm 增加 assignUser 字段
const ruleForm = reactive<RuleForm>({
  name: '',
  phone: '',
  channelId: '',
  activityId: '',
  gender: '',
  weixin: '',
  qq: '',
  businessId: '',
  departmentId: '',
  assignUser: ''
})
const departmentOptions = ref<{ label: string; value: number }[]>([])
const assignUserOptions = ref<{ label: string; value: number; departmentId: number }[]>([])
onMounted(() => {
  getList()
  getChannel()
})
// 列表
function getList() {
  list(pageParams).then(res => {
    // console.log(res)
    tableData.value = res.rows;
    total.value = res.total;
  })
}
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  pageParams.pageNum = 1
  pageParams.pageSize = val
  getList()

}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  pageParams.pageNum = val
  getList()
}
// 查询
function search() {
  pageParams.page = 1
  getList()
}
// 重置
function reset() {
  pageParams.pageNum = 1;
  pageParams.pageSize = 10;
  // 重置查询条件
  pageParams.name = '';
  pageParams.phone = '';
  pageParams.owner = '';
  value2.value = '';
  getList();
}
// 新增
const dialogFormVisible = ref(false)
const afv = ref('') // 用于绑定新增表单的 v-model
const formLabelWidth = '100px'
const form = reactive({
  name: '',
  region: '',
  date1: '',
  date2: '',
  delivery: false,
  type: [],
  resource: '',
  desc: '',
})
// 新增下拉框
function getunder() {
  under(id).then(res => {
    console.log(res);
  })
}

// 定义表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { min: 6, max: 20, message: '手机号码长度需在6-20位', trigger: 'blur' }
  ],
  departmentId: [
    { required: true, message: '请选择归属部门', trigger: 'change' }
  ],
  assignUser: [
    { required: true, message: '请选择分配用户', trigger: 'change' }
  ]
});

// 跳转到详情页面
const router = useRouter()
function goToCreate(row) {
  router.push({
    path: '/business/details',
    query: {
      name: row.name,
      phone: row.phone,
      owner: row.owner,
      qq: row.qq,
      createTime: row.createTime,
    }
  });
}

// 编辑
const id = ref<number | null>(null);
function edit() {
  if (multipleSelection.value.length !== 1) {
    ElMessage.warning('请选择一条数据进行修改');
    return;
  }
  dialogFormVisible.value = true;
  title.value = "修改商机";
  // 获取详情，主键用 businessId
  const row = multipleSelection.value[0];
  id.value = row.businessId;
  detail(row.businessId).then(res => {
    const data = res.data;
    ruleForm.name = data.name;
    ruleForm.phone = data.phone;
    ruleForm.channelId = data.channelId;
    ruleForm.activityId = data.activityId;
    ruleForm.gender = data.gender;
    ruleForm.weixin = data.weixin;
    ruleForm.qq = data.qq;
    ruleForm.businessId = data.businessId;
  });
}



const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (title.value == "添加商机") {
        // 新增接口
        add(ruleForm).then(res => {
          console.log(res);
          ElMessage({
            message: '新增成功',
            type: 'success',
          })
          dialogFormVisible.value = false

          getList();
        })
      } else {
        // 修改
        updata({
          id: id.value,
          ...ruleForm
        }).then(res => {
          ElMessage.success("修改成功")
          dialogFormVisible.value = false
          // 修改成功后直接更新表格数据，无需刷新
          const idx = tableData.value.findIndex(item => item.businessId === id.value);
          if (idx !== -1) {
            // 如果后端返回了最新数据，优先用后端数据，否则用 ruleForm
            const newData = res.data ? { ...tableData.value[idx], ...res.data } : { ...tableData.value[idx], ...ruleForm };
            tableData.value.splice(idx, 1, newData);
          }
        })

      }
    } else {
      console.log('error submit!', fields)
    }
  })
}


// 打开弹框
function show() {
  dialogFormVisible.value = true
  title.value = "添加商机"
  // 重置表单
  ruleForm.name = '';
  ruleForm.phone = '';
  ruleForm.weixin = '';
  ruleForm.qq = '';
  ruleForm.channelId = '';
  ruleForm.activityId = '';
  ruleForm.gender = '';
  nextTick(() => {
    ruleFormRef.value?.resetFields()
  })
}
//打开分配
function getxiangqing(businessId?: number) {
  if (businessId !== undefined && businessId !== null && !isNaN(Number(businessId))) {
    id.value = businessId;
    xiangqing(businessId).then(res => {
      // 递归提取所有部门节点
      function extractDepartments(nodes: any[]): { label: string; value: number }[] {
        let result: { label: string; value: number }[] = [];
        nodes.forEach(node => {
          if (node.id && node.label) {
            result.push({ label: node.label, value: node.id });
          }
          if (Array.isArray(node.children) && node.children.length > 0) {
            result = result.concat(extractDepartments(node.children));
          }
        });
        return result;
      }
      if (res && res.data && Array.isArray(res.data)) {
        departmentOptions.value = extractDepartments(res.data);
      } else {
        departmentOptions.value = [];
      }
      console.log('详情数据:', res);
    });
    getBusinessOptions(businessId).then(res => {
      if (res && Array.isArray(res.data)) {
        // 归属部门去重
        const departments = Array.from(
          new Map(res.data.map(item => [item.departmentId, {
            label: `部门${item.departmentId}`,
            value: item.departmentId
          }])).values()
        );
        departmentOptions.value = departments;
        // 分配给用户，确保 departmentId、userId 都为 number
        assignUserOptions.value = res.data.map(item => ({
          label: item.nickName,
          value: Number(item.userId),
          departmentId: Number(item.departmentId)
        }));
      } else {
        departmentOptions.value = [];
        assignUserOptions.value = [];
      }
      console.log('分配下拉数据:', res);
    });
  } else {
    departmentOptions.value = [];
    assignUserOptions.value = [];
    // id 无效时不请求，避免传递 null
    console.warn('分配时未选中有效商机id，不请求下拉数据');
  }
  dialogOverflowVisible.value = true;
  title.value = "分配商机";
}


// 批量删除
function deleteClue(event?: Event) {
  event?.preventDefault();
  if (businessId.value.length === 0) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }
  // 动态生成提示内容
  let confirmMsg = '';
  if (multipleSelection.value.length === 1) {
    confirmMsg = `是否确认删客户姓名为“${multipleSelection.value[0].name}”的数据项？`;
  } else {
    const names = multipleSelection.value.map(item => item.name).join('、');
    confirmMsg = `是否确认删除选中的${multipleSelection.value.length}条数据？`;
    // 如需显示所有姓名可用：
    // confirmMsg += `\n客户姓名：${names}`;
  }
  ElMessageBox.confirm(confirmMsg, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const ids = businessId.value;
    console.log('删除参数ids:', ids);
    clueDel(ids).then(res => {
      console.log('删除返回res:', res);
      // 兼容批量和单个删除返回
      if (Array.isArray(res)) {
        // 统计批量删除结果
        const successList = res.filter(item => item && item.data && item.data.code === 200);
        const failList = res.filter(item => !(item && item.data && item.data.code === 200));
        if (failList.length === 0) {
          ElMessage.success(`共选中${res.length}条，全部删除成功！`);
          getList();
        } else {
          // 控制台输出每个失败项的完整内容，便于排查
          failList.forEach((item, idx) => {
            // console.error(`第${idx + 1}个删除失败项：`, item?.data);
          });
          // 优先展示msg，没有msg则显示code，没有则显示原始内容
          const failMsgs = failList.map(item => {
            if (item && item.data) {
              if (item.data.msg) return item.data.msg;
              // msg 为空时，尝试拼接 code 和原始内容
              if (item.data.code) return `code:${item.data.code}`;
              return JSON.stringify(item.data);
            }
            return '未知错误';
          }).join('；');
          // 控制台输出详细失败项内容
          // console.error('批量删除失败项详情:', failList);
          getList();
        }
      } else {
        // 单个删除
        if (res.data && res.data.code === 200) {
          ElMessage.success('删除成功');
          // getList(); // 如需自动刷新可取消注释
        } else {
          ElMessage.error((res.data && res.data.msg) || '删除失败');
        }
      }
    }).catch(() => {
      ElMessage.error('删除失败，请重试');
    });
  }).catch(() => {
    // 用户取消，无操作
  });
}
// 渠道来源接口
import { channelSource } from '@/api/business/index'
const channelList = ref([])
function getChannel() {
  channelSource().then((res) => {
    console.log(res, "渠道来源");
    channelList.value = res.data;
  })
}
// 线索分配

</script>

<style>
.box {
  height: 750px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.demo-datetime-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: stretch;
}

.demo-datetime-picker .block {
  padding: 30px 0;
  text-align: center;
}

.line {
  width: 1px;
  background-color: var(--el-border-color);
}

.el-form-item__label {
  color: var(--el-text-color-regular);
}

.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

.page-container {
  position: relative;
  /* 父容器相对定位 */
  min-height: calc(100vh - 表单表格等的高度，可根据实际调整);
  /* 确保有足够空间放置绝对定位元素，也可不用，根据页面内容高度决定 */
}

.demo-pagination-block {
  position: absolute;
  bottom: -50px;
  /* 距离底部的距离，可调整 */
  right: 20px;
  /* 距离右侧的距离，可调整 */
}

.flex-right {
  display: flex;
  width: 100%;
  justify-content: space-between;
}
</style>